import React from 'react'
import { View, TextInput, TouchableOpacity } from 'react-native'
import { Controller, useFieldArray } from 'react-hook-form'
import { Icon, Text } from '@rneui/themed'
import DateTimePicker from '@react-native-community/datetimepicker'
import { leaveStyles } from '../../../styles/leaveStyles'

interface ResearchFormProps {
    control: any
    watch: any
    startDate: string
    endDate: string
    showDatePickers: { [key: string]: boolean }
    setShowDatePickers: (value: { [key: string]: boolean } | ((prev: { [key: string]: boolean }) => { [key: string]: boolean })) => void
    isEditMode?: boolean
    onMarkForDeletion?: (itemId: string) => void
    getValues?: any
}

export const ResearchForm: React.FC<ResearchFormProps> = ({
    control,
    watch: _watch,
    startDate,
    endDate,
    showDatePickers,
    setShowDatePickers,
    isEditMode = false,
    onMarkForDeletion,
    getValues
}) => {
    const researchArray = useFieldArray({ control, name: "researchItems" })

    return (
        <View style={leaveStyles.reasonFormContainer}>
            {researchArray.fields.map((field, index) => (
                <View key={field.id} style={leaveStyles.itemContainer}>
                    <Text style={leaveStyles.subLabel}>调研主题</Text>
                    <Controller
                        control={control}
                        name={`researchItems.${index}.theme`}
                        render={({ field: { onChange, value } }) => (
                            <TextInput
                                style={leaveStyles.textInput}
                                value={value}
                                onChangeText={onChange}
                                placeholder="请输入调研主题"
                            />
                        )}
                    />

                    <Text style={leaveStyles.subLabel}>调研目的</Text>
                    <Controller
                        control={control}
                        name={`researchItems.${index}.purpose`}
                        render={({ field: { onChange, value } }) => (
                            <TextInput
                                style={leaveStyles.textArea}
                                value={value}
                                onChangeText={onChange}
                                placeholder="请输入调研目的"
                                multiline={true}
                                numberOfLines={2}
                                textAlignVertical="top"
                            />
                        )}
                    />

                    <Text style={leaveStyles.subLabel}>调研单位</Text>
                    <Controller
                        control={control}
                        name={`researchItems.${index}.organization`}
                        render={({ field: { onChange, value } }) => (
                            <TextInput
                                style={leaveStyles.textInput}
                                value={value}
                                onChangeText={onChange}
                                placeholder="请输入调研单位"
                            />
                        )}
                    />

                    <Text style={leaveStyles.subLabel}>开始时间</Text>
                    <Controller
                        control={control}
                        name={`researchItems.${index}.startDate`}
                        render={({ field: { onChange, value } }) => (
                            <View>
                                <TouchableOpacity
                                    style={leaveStyles.dateButton}
                                    onPress={() => {
                                        setShowDatePickers(prev => ({ ...prev, [`research_start_${index}`]: true }))
                                    }}
                                >
                                    <Text style={leaveStyles.dateButtonText}>
                                        {value || '请选择开始时间'}
                                    </Text>
                                </TouchableOpacity>
                                {showDatePickers[`research_start_${index}`] && (
                                    <DateTimePicker
                                        value={value ? new Date(value) : new Date()}
                                        mode="date"
                                        display="default"
                                        minimumDate={startDate ? new Date(startDate) : new Date()}
                                        maximumDate={endDate ? new Date(endDate) : undefined}
                                        onChange={(event, selectedDate) => {
                                            setShowDatePickers(prev => ({ ...prev, [`research_start_${index}`]: false }))
                                            if (selectedDate) {
                                                onChange(selectedDate.toISOString().split('T')[0])
                                            }
                                        }}
                                    />
                                )}
                            </View>
                        )}
                    />

                    <Text style={leaveStyles.subLabel}>结束时间</Text>
                    <Controller
                        control={control}
                        name={`researchItems.${index}.endDate`}
                        render={({ field: { onChange, value } }) => (
                            <View>
                                <TouchableOpacity
                                    style={leaveStyles.dateButton}
                                    onPress={() => {
                                        setShowDatePickers(prev => ({ ...prev, [`research_end_${index}`]: true }))
                                    }}
                                >
                                    <Text style={leaveStyles.dateButtonText}>
                                        {value || '请选择结束时间'}
                                    </Text>
                                </TouchableOpacity>
                                {showDatePickers[`research_end_${index}`] && (
                                    <DateTimePicker
                                        value={value ? new Date(value) : new Date()}
                                        mode="date"
                                        display="default"
                                        minimumDate={startDate ? new Date(startDate) : new Date()}
                                        maximumDate={endDate ? new Date(endDate) : undefined}
                                        onChange={(event, selectedDate) => {
                                            setShowDatePickers(prev => ({ ...prev, [`research_end_${index}`]: false }))
                                            if (selectedDate) {
                                                onChange(selectedDate.toISOString().split('T')[0])
                                            }
                                        }}
                                    />
                                )}
                            </View>
                        )}
                    />

                    {researchArray.fields.length > 1 && (
                        <View style={leaveStyles.deleteButtonContainer}>
                            <Icon
                                name="close"
                                type="material"
                                size={20}
                                color="white"
                                containerStyle={leaveStyles.circularDeleteButton}
                                onPress={() => {
                                    if (isEditMode && onMarkForDeletion) {
                                        const currentFormData = getValues()
                                        const realId = currentFormData.researchItems?.[index]?.id
                                        if (realId && typeof realId === 'number') {
                                            onMarkForDeletion(realId.toString())
                                        }
                                        researchArray.remove(index)
                                    } else {
                                        researchArray.remove(index)
                                    }
                                }}
                            />
                        </View>
                    )}
                </View>
            ))}
            <View style={leaveStyles.addButtonContainer}>
                <TouchableOpacity
                    style={leaveStyles.circularAddButton}
                    onPress={() => researchArray.append({ startDate: startDate || "", endDate: endDate || "", theme: "", purpose: "", organization: "" })}
                >
                    <Icon
                        name="add"
                        type="material"
                        size={20}
                        color="white"
                    />
                </TouchableOpacity>
            </View>
        </View>
    )
}
